package com.dao.impl;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dao.QuestionActionDAO;
import com.model.QuestionAction;
@Repository
public class QuestionActionDAOImpl implements QuestionActionDAO {
	@Autowired
    private SessionFactory sessionFactory;

	public void add(QuestionAction qa) {
		sessionFactory.getCurrentSession().save(qa);
		
	}

	public boolean isExist(int qid, int uid, String action) {
		try{
			String sql = "";
			if("favor".equals(action)){
				sql = "select count(*) from question_action as qa where qa.user_id=:userId and qa.question_id=:questionId and qa.action_type='favor'";
			}else if("agree".equals(action) || "disagree".equals(action)){
				sql = "select count(*) from question_action as qa where  qa.user_id=:userId and qa.question_id=:questionId and (qa.action_type='agree' or qa.action_type='disagree')";
			}else if("collect".equals(action)){
				sql = "select count(*) from question_action as qa where qa.user_id=:userId and qa.question_id=:questionId and qa.action_type='collect'";
			}else{
				return false;
			}

			Session s = sessionFactory.getCurrentSession();
			Query query = s.createSQLQuery(sql);
			query.setInteger("questionId", qid);
			query.setInteger("userId", uid);
			
			int count = Integer.parseInt((query.uniqueResult().toString()));
	
			if(count > 0){
				return true;
			}else{
				return false;
			}
		}catch (Exception e){
			System.out.println(e.getMessage());
		}
		return false;
	}

	public void cancelCollectQuestion(int questionId, int userId) {
		Session s = sessionFactory.getCurrentSession();
		String sql = "delete from question_action where question_id=:questionId and user_id=:userId and action_type='collect'";
		Query q = s.createSQLQuery(sql);
		q.setInteger("questionId", questionId);
		q.setInteger("userId", userId);
		q.executeUpdate();
	}
	
	
}
